package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.NewsAuthDto;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.media.service.IWmUserService;
import com.heima.media.vo.WmNewsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-06-29
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {

        //判断是否有登录人
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 构建条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        // 状态
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        // 开始时间
        if (dto.getBeginPubDate() != null) {
            queryWrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        //结束时间
        if (dto.getEndPubDate() != null) {
            queryWrapper.le(WmNews::getPublishTime, dto.getEndPubDate());
        }
        //频道
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //关键字
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //隐藏条件：1、排序 2、当前登录人
        queryWrapper.eq(WmNews::getUserId, user.getUserId());

        queryWrapper.orderByDesc(WmNews::getPublishTime);


        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> page1 = this.page(page, queryWrapper);

        return new PageResponseResult(dto.getPage(), dto.getSize(), page1.getTotal(), page1.getRecords());
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //判断是否有人登录
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判断是否有id
        if (dto.getId() != null) {
            //根据自媒体文章id,删除已关联的表关系
            deleteRelation(dto.getId());
        }
        //开始构建自媒体文章对象
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());
        //dto中的images是集合,表重要的是一个字符串
        wmNews.setImages(JSON.toJSONString(dto.getImages()));
        //wmNews.setStatus();  //提交为1  草稿为0
        //wmNews.setType();  有逻辑   0 无图 1 单图 3 多图 -1 自动

        //从内容中获取所有的图片
        List<ImageDto> imagesFromContent = getImagesFromContent(dto.getContent());
        if (dto.getType() == -1) {//说明封面图片是从文章内容中获取的
            int size = imagesFromContent.size();
            if (size <= 0) {
                wmNews.setType(0);
            } else if (size > 0 && size < 3) {
                wmNews.setType(1);
                List<ImageDto> imageDtoList = imagesFromContent.subList(0, 1);
                wmNews.setImages(JSON.toJSONString(imageDtoList));
            } else {
                wmNews.setType(3);
                List<ImageDto> imageDtoList = imagesFromContent.subList(0, 3);
                wmNews.setImages(JSON.toJSONString(imageDtoList));
            }

        }
        //新增文章或者修改文章
        this.saveOrUpdate(wmNews);
        //判断是否为草稿
        if (dto.getStatus() == 1) {
            //保存文章内容图片和素材之间的关系
            saveRelation(imagesFromContent, wmNews.getId(), 0);
            //保存文章封面图片和素材之间的关系
            List<ImageDto> imageDtoList = JSON.parseArray(wmNews.getImages(), ImageDto.class);
            saveRelation(imageDtoList, wmNews.getId(), 1);
        }

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findPageByName(NewsAuthDto dto) {
        // 构建查询条件
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        // 根据标题模糊查询
        if (!StringUtils.isEmpty(dto.getTitle())) {
            query.like(WmNews::getTitle, dto.getTitle());
        }
        // 根据状态查询
        if (dto.getStatus() != null) {
            query.eq(WmNews::getStatus, dto.getStatus());
        }
        // 根据发布时间倒序排列
        query.orderByDesc(WmNews::getPublishTime);

        // 构建分页条件
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        // 分页查询
        IPage<WmNews> iPage = this.page(page, query);
        List<WmNews> newsList = iPage.getRecords();
        // 返回通用的分页响应
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                iPage.getTotal(), newsList);
        return result;
    }
    @Autowired
    private IWmUserService userService;
    @Override
    public ResponseResult<WmNewsVo> findNewsVoById(Integer id) {
        // 根据id查询文章
        WmNews wmNews = this.getById(id);
        // 查询作者名称
        WmUser wmUser = userService.getById(wmNews.getUserId());
        // 构建vo对象
        WmNewsVo vo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, vo);
        vo.setAuthorName(wmUser.getName());
        // 通用响应
        return ResponseResult.okResult(vo);
    }
    private IAuditService auditService;
    @Override
    public ResponseResult auth(NewsAuthDto dto, int i) {
        // 根据文章id查询
        WmNews wmNews = this.getById(dto.getId());
        // 如果是审核通过,修改状态为4
        if (i == 1) {
            // 发布文章
            Long articleId = auditService.saveArticle(wmNews);
            wmNews.setArticleId(articleId);
            wmNews.setStatus(4);
            this.updateById(wmNews);

        } else {
            // 审核不通过,记录拒绝原因
            wmNews.setStatus(2);
            wmNews.setReason(dto.getMsg());
            this.updateById(wmNews);
        }
        return ResponseResult.okResult();
    }
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Value("${topic.upDownTopic}")
    private String topicUpDownTopic;
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //        1、判断是否有登录人
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        if(dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = this.getById(dto.getId());
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Map map=new HashMap();
        map.put("articleId",wmNews.getArticleId());
        map.put("enable",dto.getEnable()==1?true:false);
        kafkaTemplate.send(topicUpDownTopic,JSON.toJSONString(map));
        return ResponseResult.okResult();
    }

    @Autowired
    private IWmNewsMaterialService newsMaterialService;

    //保存内容图片、封面图片与素材的关系
    private void saveRelation(List<ImageDto> imageDtoList, Integer id, int type) {
        int i = 0;
        for (ImageDto imageDto : imageDtoList) {
            WmNewsMaterial newsMaterial = new WmNewsMaterial();
            newsMaterial.setMaterialId(imageDto.getId());
            newsMaterial.setNewsId(id);
            newsMaterial.setType(type);
            newsMaterial.setOrd(i++);
            newsMaterialService.save(newsMaterial);
        }
    }
    //从内容中获取所有的图片
    private List<ImageDto> getImagesFromContent(String content) {
        List<ImageDto> imageDtoList =new ArrayList<>();
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imageDtoList.add(imageDto);
            }
        }
        return imageDtoList;
    }
    //    根据自媒体文章id 删除已关联的素材关系
    private void deleteRelation(Integer newsId) {
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId,newsId);
        newsMaterialService.remove(queryWrapper);
    }
}
